/**
 * @author meyoo
 * @date 2018/3/29
 * @Description:
*/
var Config = require("./Config.js")
var UnitTools = require("./UnitTools.js")
var fs = require("fs")
class IDs{
    //初始化
    constructor(){

    }
    initFromConfig(){
        //配置文件中创建随机数id文件
        this.idConfig = Config.getServerConfig().ids;
        if(this.idConfig["create"]){
            //需要创建ids
            this.generateIdsToFiles(this.idConfig.from,this.idConfig.to,__dirname+"/../"+this.idConfig.idspath,__dirname+"/../"+this.idConfig.countpath)
        }


    }
    //生成id的数组
    generateIdsToFiles(from,to,IDsPath,countPath){
        var countNum = to -from + 1;
        var idsBuffer = new Buffer(countNum*4);
        for (var i = from; i <= to; i++) {
            var start = i - from;
            start = start * 4;
            idsBuffer.writeUInt32LE(i,start);
        }
        //buff中的id打乱顺序
        for (var i = 0; i < countNum; i++) {
            var randomIndex = UnitTools.random(0,countNum-1);
            var curNumber = idsBuffer.readUInt32LE(i*4);
            var changeNumber = idsBuffer.readUInt32LE(randomIndex*4);
            idsBuffer.writeUInt32LE(changeNumber,i*4);
            idsBuffer.writeUInt32LE(curNumber,randomIndex*4);
        }
        //    保存文件
        fs.writeFileSync(IDsPath,idsBuffer,{flag:"w"});
        fs.writeFileSync(countPath,0,{flag:"w"});

    }
    async getID(){
        //读取ids
         var self = this
        return new Promise(function (resolve,reject) {
            var numacount = parseInt(fs.readFileSync(__dirname+"/../"+self.idConfig.countpath,"utf-8"));
            var startIndex = numacount*4;
            //{ start: 90, end: 99 }
            var stream = fs.createReadStream(__dirname+"/../"+self.idConfig.idspath,{ start: startIndex, end: startIndex+4 ,flags:"r"});
            stream.on("data",function(buffdata) {
                var id = buffdata.readUInt32LE(0);
                fs.writeFileSync(__dirname+"/../"+self.idConfig.countpath,numacount+1);
                resolve(id);

            })
        })
    }
}
module.exports = IDs;